<!--
 * @Description:联想输入
 * @Autor: LJF
 * @Date: 2021年8月10日 16:36:48
 * @LastEditors:  
 * @LastEditTime:
-->
<template>
  <el-select
    v-model="value"
    multiple
    filterable
    remote
    reserve-keyword
    placeholder="请输入关键词"
    :remote-method="remoteMethod"
    :loading="loading"
  >
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>  
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs, onUnmounted } from 'vue'
import dataSourceManager from '@/utils/dataSourceManager'
export default defineComponent({
  props: {
    dataSourceType: {
      type: Number,
      default: 0
    },
    id: { // 控件唯一标识 防止一个页面中多个重复
      type: Number,
      default: 1
    },
    filed: {
      type: String,
      defualt: ''
    }
  },
  emits: ['dataSourceReady', 'searchReady'],
  setup(props, ctx) {
    const state = reactive({
      options: [],
      value: props.filed,
      loading: false,
      remoteMethod: function(key: string) { 
        if (!key) {
          return
        }
        state.options = dataSourceManager.getFilterArray(key) as any
        ctx.emit('searchReady', { id: props.id });
      }
    })

    const getUrl = (type: number) => {
      switch (type) {
        case 1: // 1. 公司  2. 部门 3 个人
              
          return 'http://pre.hyfiles.com/ms/data2/user/employee.js?_=20210707092654';
      
        default:
          return 'http://pre.hyfiles.com/ms/data2/user/company-all.js?_=20210707112752';
      }
    }
    
    onMounted(() => {
      if (props.dataSourceType > 0 && getUrl(props.dataSourceType)) {
        dataSourceManager.initDataSource(
          getUrl(props.dataSourceType),
          (el) => ({
            value: el.ID,
            label: el.Name,
            code: el.Extend
          }),
          () => { 
            state.options = dataSourceManager.getFilterArray('') as any;
            ctx.emit('dataSourceReady', { id: props.id });
          }
        )
      }
    })

    onUnmounted(() => {
      dataSourceManager && dataSourceManager.destroy()    
    })

    return {
      ...toRefs(state)
    }
  }
})
</script>
